package mspdt.ontrade;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.modifier.ScaleModifier;
import org.andengine.entity.modifier.SequenceEntityModifier;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.scene.background.SpriteBackground;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.util.GLState;
import org.andengine.opengl.view.RenderSurfaceView;
import org.andengine.ui.activity.LayoutGameActivity;
import org.andengine.util.debug.Debug;
import org.andengine.util.modifier.IModifier;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ViewFlipper;

public class MainActivity extends LayoutGameActivity {

	ViewFlipper flipper = null;
	float downY = 0f, upY = 0f;
	Animation downIn;
	Animation downOut;
	Animation upIn;
    Animation upOut;
    int index = 1;
    RenderSurfaceView main_surface;
    private Sound sound_click;
    ImageView category = null, game = null;
    LinearLayout main_ll = null;
    LinearLayout f_ll_1, f_ll_2, f_ll_3, f_ll_4, f_ll_5, f_ll_6, f_ll_7, f_ll_8;
    private static final int CAMERA_WIDTH = 480;
	private static final int CAMERA_HEIGHT = 650;
	private Camera mCamera;
	private Scene mainScene;
	
    boolean clicked = false;
    boolean isCategory = true;
    public void down(View v)
    {
    	flipper.setInAnimation(downIn);
    	flipper.setOutAnimation(downOut);
    	flipper.showNext();
    	index++;
    	if(index>8)
    		index = 1;
    }
    public void up(View v)
    {
    	flipper.setInAnimation(upIn);
    	flipper.setOutAnimation(upOut);
    	flipper.showPrevious();
    	index--;
    	if(index == 0)
    		index =8;
    }
    public void gamesActivity(View v)
    {
    	isCategory = false;
    	category.setImageResource(R.drawable.menu1_clicked);
    	game.setImageResource(R.drawable.menu2);
    	main_ll.setBackgroundColor(Color.WHITE);
    	main_surface.setVisibility(View.VISIBLE);
    	//startActivity(new Intent(this, GamesActivity.class));
    }
    public void categoryActivity(View v)
    {
    	isCategory = true;
    	category.setImageResource(R.drawable.menu1);
    	game.setImageResource(R.drawable.menu2_clicked);
    	main_ll.setBackgroundColor(Color.TRANSPARENT);
    	main_surface.setVisibility(View.GONE);
    	//startActivity(new Intent(this, GamesActivity.class));
    }

    
    @Override
    public void onResume()
    {
    	super.onResume();
    	Log.d("TEST", "resume");
    }
	@Override
	public EngineOptions onCreateEngineOptions() {
		// TODO Auto-generated method stub
		Log.d("TEST", "engineoptions");
		mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new FillResolutionPolicy(), mCamera);
		mCamera.setZClippingPlanes(-100, 100);
		engineOptions.getAudioOptions().setNeedsSound(true);
		return engineOptions;
	}

	@Override
	public void onCreateResources(
			OnCreateResourcesCallback pOnCreateResourcesCallback)
			throws Exception {
		Log.d("TEST", "CreateResources");
		// TODO Auto-generated method stub
		SoundFactory.setAssetBasePath("mfx/");
		try {
			this.sound_click = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "click.mp3");
		} catch (final IOException e) {
			Debug.e(e);
		}
		pOnCreateResourcesCallback.onCreateResourcesFinished();
	}

	@Override
	public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
			throws Exception {
		Log.d("TEST", "CreateScene");
		// TODO Auto-generated method stub
		mainScene = new Scene();
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("pic/");
		BitmapTextureAtlas bgTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 768, 1024, TextureOptions.DEFAULT);
		ITextureRegion bgTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bgTextureAtlas, this, "main_background.jpg", 0, 0);
		bgTextureAtlas.load();
		Sprite bgSprite = new Sprite(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, bgTextureRegion, mEngine.getVertexBufferObjectManager())
		{
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				//if(devil!=Integer.parseInt(this.getUserData().toString()))
					//this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
				//male.clearEntityModifiers();
				return true;
			}
		};
		SpriteBackground bg = new SpriteBackground(bgSprite);
		mainScene.setBackground(bg);
		
		
		
		
		String[] menu_images = {"game1_select.png", "game2_select.png", "game3_select.png", "game4_select.png"};
		float[] menuX = {60f, 270f, 60f, 270f};
		float[] menuY = {30f, 30f, 250f, 250f};
		for(int i=0;i<4;i++)
		{
			BitmapTextureAtlas bottlesTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 288, 288, TextureOptions.DEFAULT);
			ITextureRegion bottlesTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bottlesTextureAtlas, this, menu_images[i], 0, 0);
			bottlesTextureAtlas.load();
			final Sprite menus = new Sprite(menuX[i], menuY[i], 150, 150, bottlesTextureRegion, this.getVertexBufferObjectManager()) 
			{
				@Override
				protected void applyRotation(final GLState pGLState) {
					final float rotation = this.mRotation;

					if(rotation != 0) {
						final float rotationCenterX = this.mRotationCenterX;
						final float rotationCenterY = this.mRotationCenterY;

						pGLState.translateModelViewGLMatrixf(rotationCenterX, rotationCenterY, 0);
						/* Note we are applying rotation around the y-axis and not the z-axis anymore! */
						pGLState.rotateModelViewGLMatrixf(rotation, 0, 1, 0);
						pGLState.translateModelViewGLMatrixf(-rotationCenterX, -rotationCenterY, 0);
					}
				}
				@Override
				public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) 
				{
					if(TouchEvent.ACTION_DOWN== pSceneTouchEvent.getAction())
					{
						this.registerEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.3f, 1.0f, 1.2f), new ScaleModifier(0.3f, 1.2f, 1f)));
					}
					else if(TouchEvent.ACTION_UP == pSceneTouchEvent.getAction())
					{
						if(!clicked)
						{
							clicked = true;
							this.registerEntityModifier(new ScaleModifier(0.3f, 1.2f, 1f));
							this.registerEntityModifier(new SequenceEntityModifier(new IEntityModifierListener() {
								@Override
								public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
									MainActivity.this.runOnUiThread(new Runnable() {
										@Override
										public void run() {
											sound_click.play();
											//Toast.makeText(Game1Activity.this, "Sequence started.", Toast.LENGTH_SHORT).show();
										}
									});
								}

								@Override
								public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
									MainActivity.this.runOnUiThread(new Runnable() {
										@Override
										public void run() {
											if(Integer.parseInt(pEntity.getUserData().toString())==0)
												startActivity(new Intent(MainActivity.this, Game1Activity.class));
											else if(Integer.parseInt(pEntity.getUserData().toString())==1)
												startActivity(new Intent(MainActivity.this, Game2Activity.class));
											else if(Integer.parseInt(pEntity.getUserData().toString())==2)
												startActivity(new Intent(MainActivity.this, Game3Activity.class));
											else if(Integer.parseInt(pEntity.getUserData().toString())==3)
												startActivity(new Intent(MainActivity.this, Game4Activity.class));
											clicked = false;
										}
									});
								}
							}, new RotationModifier(0.3f, 0, 360)));
						}
					}
					return true;
				}
				
				
			};
			//menus.setScaleY(1.2f);

			menus.setUserData(i);
			mainScene.attachChild(menus);
			mainScene.registerTouchArea(menus);
		}
		//mainScene.setChildScene(menuScene, false, true, true);
		pOnCreateSceneCallback.onCreateSceneFinished(this.mainScene);
	}

	@Override
	public void onPopulateScene(Scene pScene,
			OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
		Log.d("TEST", "PopulateScene");
		// TODO Auto-generated method stub
		pOnPopulateSceneCallback.onPopulateSceneFinished();
	}

	@Override
	protected int getLayoutID() {
		Log.d("TEST", "getLayoutID");
		// TODO Auto-generated method stub
		return R.layout.activity_main;
		
	}

	@Override
	protected int getRenderSurfaceViewID() {
		Log.d("TEST", "RenderSurfaceViewId");
		// TODO Auto-generated method stub
		return R.id.main_surface;
	}
	
	@Override
	public void onSetContentView()
	{
		
		super.onSetContentView();
		Log.d("TEST", "SetContentView");
			downIn = AnimationUtils.loadAnimation(this, R.anim.push_down_in);
	      downOut = AnimationUtils.loadAnimation(this, R.anim.push_down_out);
	      upIn = AnimationUtils.loadAnimation(this, R.anim.push_up_in);
	      upOut = AnimationUtils.loadAnimation(this, R.anim.push_up_out);	
	      
	      flipper = (ViewFlipper)findViewById(R.id.flipper);
	      flipper.setBackgroundColor(Color.WHITE);
	      flipper.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					if(isCategory)
					{
						if(MotionEvent.ACTION_DOWN == event.getAction())
						{
							downY = event.getY();
						}
						else if(MotionEvent.ACTION_UP == event.getAction())
						{
							upY = event.getY();
							if(downY-upY > 30)
							{
								up(new View(MainActivity.this));
							}
							else if(downY-upY < -30)
							{
								down(new View(MainActivity.this));
							}
							else
							{
								Bundle bundle = new Bundle();
								
								Intent product = new Intent(getApplicationContext(), ViewProduct.class);
								
								switch(index)
								{
								case 1: bundle.putInt("ID", 3); break;
								case 2: bundle.putInt("ID", 2); break;
								case 3: bundle.putInt("ID", 1); break;
								case 4: bundle.putInt("ID", 4); break;
								case 5: bundle.putInt("ID", 5); break;
								case 6: bundle.putInt("ID", 6); break;
								case 7: bundle.putInt("ID", 7); break;
								case 8: bundle.putInt("ID", 8); break;
								default: break;
								}
								product.putExtras(bundle);
								startActivity(product);
							}
							downY = 0;
							upY = 0;
						}
					}
					return true;
				}
			});
	      f_ll_1 = (LinearLayout)findViewById(R.id.flipchild_1);
	      f_ll_2 = (LinearLayout)findViewById(R.id.flipchild_2);
	      f_ll_3 = (LinearLayout)findViewById(R.id.flipchild_3);
	      f_ll_4 = (LinearLayout)findViewById(R.id.flipchild_4);
	      f_ll_5 = (LinearLayout)findViewById(R.id.flipchild_5);
	      f_ll_6 = (LinearLayout)findViewById(R.id.flipchild_6);
	      f_ll_7 = (LinearLayout)findViewById(R.id.flipchild_7);
	      f_ll_8 = (LinearLayout)findViewById(R.id.flipchild_8);
	      
	      
	      
	      
	      try {
				f_ll_1.setBackgroundDrawable(getAssetImage(this, "flip3"));
				f_ll_2.setBackgroundDrawable(getAssetImage(this, "flip2"));
				f_ll_3.setBackgroundDrawable(getAssetImage(this, "flip1"));
				f_ll_4.setBackgroundDrawable(getAssetImage(this, "flip4"));
				f_ll_5.setBackgroundDrawable(getAssetImage(this, "flip5"));
				f_ll_6.setBackgroundDrawable(getAssetImage(this, "flip6"));
				f_ll_7.setBackgroundDrawable(getAssetImage(this, "flip7"));
				f_ll_8.setBackgroundDrawable(getAssetImage(this, "flip8"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	      
	      
	      main_surface = (RenderSurfaceView)findViewById(R.id.main_surface);
	      main_surface.setVisibility(View.GONE);
	      category = (ImageView)findViewById(R.id.btn_cate);
	      game = (ImageView)findViewById(R.id.btn_game);
	      main_ll = (LinearLayout)findViewById(R.id.main_background);
	      main_ll.setBackgroundColor(Color.TRANSPARENT);
	}
	
	public static Drawable getAssetImage(Context context, String filename) throws IOException {
	    AssetManager assets = context.getResources().getAssets();
	    InputStream buffer = new BufferedInputStream((assets.open("pic/" + filename + ".jpg")));
	    Bitmap bitmap = BitmapFactory.decodeStream(buffer);
	    return new BitmapDrawable(bitmap);
	}
	
	public void toInfo(View v)
	{
		startActivity(new Intent(MainActivity.this, Information.class));
	}
}
